/*
 * @Author: xiaosihan
 * @Date: 2024-07-11 10:22:49
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-08-01 15:38:26
 */
import express from 'express';
import fs from 'fs';
import { get, isEmpty } from 'lodash';
import path from 'path';

// 服务基类
export default class ServiceBase {
  constructor() {}

  // 提取post get参数
  getParame(req: express.Request) {
    return { ...(get(req, ['user']) || {}), ...(get(req, ['adminUser']) || {}), ...req.query, ...req.body };
  }

  // 判断是否登录
  isLogin(req: express.Request) {
    return !isEmpty(get(req, ['user']));
  }

  // 判断是否管理员
  isAdmin(req: express.Request) {
    return !isEmpty(get(req, ['adminUser']));
  }

  //创建一个判空的中间件
  paramNotEmpty(params: Array<string>) {
    return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
      const emptyParam = [];
      for (let p of params) {
        if (isEmpty(req.params[p]) && isEmpty(req.body[p])) {
          // 记录空参数
          emptyParam.push(p);
        }
      }

      if (isEmpty(emptyParam)) {
        next();
      } else {
        this.error(res, `${emptyParam.join(',')}不能为空`);
      }
    };
  }

  // 递归读取文件
  async walkDir(directory: string, callback: Function) {
    return new Promise<void>((resolve, reject) => {
      fs.readdir(directory, async (err, files) => {
        if (err) return console.error(err);

        for (let file of files) {
          const fullPath = path.join(directory, file);

          await new Promise<void>((resolve2, reject) => {
            fs.stat(fullPath, (err, stats) => {
              if (err) return console.error(err);

              if (stats.isDirectory()) {
                this.walkDir(fullPath, callback);
                resolve2();
              } else if (stats.isFile()) {
                callback(fullPath);
                resolve2();
              }
            });
          });
        }
        resolve();
      });
    });
  }

  // 获取文件名的后缀
  getSuffix(filename: string) {
    const match = filename.match(/\.([^\.]+)$/);
    return match ? match[1].toLowerCase() : '';
  }

  // 返回成功的状态
  success(res: express.Response, data: any = undefined, message = '成功') {
    if (get(res, ['_headerSent'])) return;
    res.send({
      status: 'success',
      code: 200,
      message,
      data,
    });
  }

  //返回失败的状态
  error(res: express.Response, message = '失败') {
    if (get(res, ['_headerSent'])) return;
    res.send({
      status: 'error',
      code: 401,
      message,
    });
  }
}
